﻿using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using QuickGet.Core.Models;
using QuickGet.Core.Stores;

namespace QuickGet.Endpoints
{
    public static class PackageSourceEndpoints
    {
        public static IEndpointRouteBuilder MapPackageSourceEndpoints(this IEndpointRouteBuilder endpoints)
        {
            var group = endpoints.MapGroup("/package-source").WithTags("PackageSource");

            group.MapGet("/list", ListPackageSources).WithName(nameof(ListPackageSources));
            group.MapPost("/set-enable", SetPackageSourceEnabled).WithName(nameof(SetPackageSourceEnabled));
            group.MapPost("/create", CreatePackageSource).WithName(nameof(CreatePackageSource));

            return endpoints;
        }

        public static async Task<Ok<List<PackageSourceInfo>>> ListPackageSources([FromServices] IPackageSourceStore store)
        {
            return TypedResults.Ok(await store.ListAsync(CancellationToken.None));
        }

        public static async Task SetPackageSourceEnabled(
            [FromQuery] string name,
            [FromQuery] bool enabled,
            [FromServices] IPackageSourceStore store)
        {
            await store.SetEnabledAsync(name, enabled, CancellationToken.None);
        }

        public static async Task CreatePackageSource(
            [FromQuery] string name,
            [FromQuery] string source,
            [FromServices] IPackageSourceStore store)
        {
            await store.CreateAsync(new PackageSourceInfo(name, source, true), CancellationToken.None);
        }
    }
}
